/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3net.
 *
 *  e3net is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3net is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3net. If not, see <https://www.gnu.org/licenses/>.
 */

package packet

import (
	"io"
)

var DefaultPackHandler PackHandler = &defaultPackHandler{}

type Writer interface {
	io.Writer
	GetPacketSize() int //每个消息包大小
}

// PackHandler 打包拆包接口
type PackHandler interface {
	UnPack(readBuff, writeBuff []byte) (readSize int, out []byte, err error) //解包
	Pack(readBuff, writeBuff []byte) (writeSize int, err error)              //封包
}

// defaultPackHandler 默认 PackHandler
type defaultPackHandler struct{}

// UnPack 拆包
func (ts *defaultPackHandler) UnPack(readBuff, writeBuff []byte) (packSize int, out []byte, err error) {
	rdBufferSize := len(readBuff)
	if rdBufferSize < HeadSize {
		return 0, nil, nil
	}
	h := newHeadWarp(readBuff[:HeadSize])
	wn := int(h.bodySize())
	packSize = HeadSize + wn
	if rdBufferSize < packSize {
		return packSize, nil, nil
	}
	if wn > len(writeBuff) {
		return 0, nil, io.ErrShortWrite
	}
	copy(writeBuff[0:], readBuff[HeadSize:packSize])
	return packSize, writeBuff[:wn], nil
}

// Pack 封包
func (ts *defaultPackHandler) Pack(readBuff, writeBuff []byte) (writeSize int, err error) {
	dataSize := len(readBuff)
	writeSize = dataSize + HeadSize
	if writeSize > len(writeBuff) {
		return 0, io.ErrShortWrite
	}
	h := newHeadWarp(writeBuff[:HeadSize])
	h.init()
	h.setBodySize(uint16(dataSize))
	copy(writeBuff[HeadSize:], readBuff[0:])
	return writeSize, nil
}
